<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Views\Index;

use Sun\Sun;
use Sun\Html;
use Sun\Utils;
use Sun\Html\Form;
use App\Models;
use App\Models\DB;

class Catalog extends Main {
    private $edit;
    public function __construct() {
        parent::__construct("Body");
        $this->title = "Каталог";
        $this->tab = "MenuCatalog";

        $this->edit = new Models\Edition();
    }


    public function DictionaryScene() {
        $edit = new Models\Edition();
        $cond = !empty($this->data['rec'])
            ? "lower(value) LIKE lower(".$edit->db->quote($this->data['rec']."%").")"
            : "true";

        $num_rows = Sun::conf("iface/dict_rows");
        $num_pages = ceil($edit->GetCatalogNumDictRecs($this->data['field_id'], $cond) / $num_rows);

        $p = $this->data['Page'];
        $offset = $num_rows * ($p - 1);

        $res = $edit->GetCatalogDictRecs($this->data['field_id'], $cond, $offset, $num_rows);

        $table = new Html\QueryTable($res, array("Значение"), false);
        $table->SetAttribute("class", $table->Attribute('class').' Dictionary CatalogDict');
        $table->SetAttribute("id", "RecTable");
        $table->SetAttribute("data-field", $this->data['field_id']);

        //////////////////////////////////////////
        $src = Utils::LoadFileToString(dirname(__FILE__)."/Catalog/Dictionary.js");
        $script = new Html\Script($src, array('id' => "CatalogDictRecScript"));
        //////////////////////////////////////////

        $div = new Html\Div();
        $div->Add($table);
        $div->Add($script);

        $cont = $div->ToJson();
        $query_res = "{ content: {$cont}, num_pages: {$num_pages} }";

        echo $query_res;
    }

    //public function SearchResultScene() {

        //$res = $this->edit->CatalogSearch($this->data);
        //$edit = $this->EditBrief($res['RES'])->ToJson();

        //echo $edit;
    //}


    public function SortField() {
        $fields = $this->edit->GetFieldsData();
        $select = new Form\Select(array('id' => "SortField", 'style' => "max-width: 200px"));
        foreach ($fields as $field) {
            if ($field['sense'] == "STR") {
                $option = new Form\Option($field['field_id'], $field['name']);
                $select->Add($option);
            }
        }
        return $select;
    }

    public function EditTypes() {
        $types = $this->edit->GetEditionTypes();
        $select = new Form\Select(array('id' => "EditType"));
        foreach ($types as $type) {
            $select->AddOption($type['type_id'], $type['name']);
        }
        return $select->ToHtml();
    }

    public function FieldTypes() {
        $select = new Form\Select(array('id' => "FieldType", 'style' => "max-width: 150px"));
        $fields = $this->edit->GetCatalogFields();
        foreach ($fields as $field) {
            $select->AddOption($field['field_id'], $field['name']);
        }
        return $select->ToHtml();
    }


    public function EditBrief($edits, $start) {

        $rows = array();
        foreach ($edits as $e) {
            $rows[] = array($this->edit->GetEditDetailBrief($e[0]));
        }

        $table = new Html\QueryTable($rows, Array("Описание"));
        $table->id = "EditList";
        $table->style = "width: 100%";

        $usr = new Models\User();
        $sess = new Models\Session();

        if ($sess->UserType() == "READ" || $sess->UserType() == 'TEACH') {
            $rows = $table->First()->Childs();

            $rows[0]->AddFirst(new Html\TData())->Added()->Add(new Html\Text('№'));

            $rows[0]->AddData()->Added()->SetAttribute('class', 'ControlCell');

            for ($i = 1; $i < count($rows); ++$i) {
                $id = $edits[$i - 1][0];
                $num = $start + $i;
                $rows[$i]->SetAttribute("data-id", $id)
                    ->AddFirst(new Html\TData())
                    ->Added()->SetAttribute('class', 'ControlCell')
                        ->Add(new Html\Text($num));

                $rows[$i]->AddData()->Added()->SetAttribute('class', 'ControlCell')
                         ->Add(new Html\Form\Input('checkbox', array('data-id' => $id)));
            }
        }

        ////////////////// javascript //////////////////////
        $src = Utils::LoadFileToString(dirname(__FILE__)."/Search/Search.js");
        $script = new Html\Script($src, array('id' => "Search"));
        ////////////////////////////////////////////////////

        $div = new Html\Div();
        $div->Add($table);
        $div->Add($script);
        return $div;
    }

    public function DictionarySwitch() {
        $page_switch = new Html\PageSwitch("CatalogDictionary", 9);
        $div = $page_switch->Div();
        $div->SetAttribute('class', 'Catalog '.$div->Attribute('class'));
        return $page_switch;
    }


    public function ControllElements() {
        $sess = new Models\Session();
        if ($sess->UserType() == 'READ' || $sess->UserType() == 'TEACH') {
            $set = new Html\HtmlSet();

            $order = new Html\HtmlContainer('button');
            $order->id = 'GoToOrder';
            $order->Add(new Html\Text('Оформить заказ'));

            $clear = new Html\HtmlContainer('button');
            $clear->id = 'ClearSelectin';
            $clear->Add(new Html\Text('Очистить'));
            $set->Add($clear)->Add(new Html\Text(' '))->Add($order);
            return $set->ToHtml();
        }
        return "";
    }

    public function SearchResultScene() {
        $this->data['num'] = 10;
        $page = @$this->data['Page'];
        $page = $page ? $page : 1;

        $offset = ($page - 1) * $this->data['num'];

        $res = $this->edit->CatalogSearch($this->data, $offset);

        $pages = ceil($res['NUM'] / $this->data['num']);
        $edit = $this->EditBrief($res['RESULT'], $offset);

        $cont = $edit->ToJson();

        echo "{ content: {$cont}, num_pages: {$pages} }";
    }

    public function SearchResultSwitch() {
        $page_switch = new Html\PageSwitch("CatalogResult");

        $div = $page_switch->Div();
        $div->SetAttribute('class', 'Search '.$div->Attribute('class'));

        return $page_switch;
    }

}
